package org.dromara.hmily.demo.springcloud.order.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
	public  Object bizExceptionHandler(HttpServletRequest req, Exception e){
    	this.exceptionLogs(e,req);
    	logger.error("发生业务异常！原因是：{}",e.getMessage());
    	return "false";
    }

	public void exceptionLogs(Exception e, HttpServletRequest request) {
		try {
			//日志打印
			log.error("BaseController->exceptionHandler:request url:[{}],request params:[{}];exception:[{}]", request.getRequestURI(), RequestUtils.getRequestJsonString(request), ExceptionUtils.getStackTrace(e));
		} catch (IOException ex) {
			log.error("BaseController getting parameter exceptions");
		}
	}
}